# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://manhua.dmzj.com/comic_name/ 解析器
#
#*******************************************************************************
from base import *

tag='dmzj'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://manhua.dmzj.com/\w+/',url):
        return valid_check(url)
    return False

# 根据内容检测是否可解析
def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

def get_loader(url):
    return DmzjLoader(url,DmzjPageParser,DmzjVolParser)

#---------------------------- 下载器 ----------------------------

class DmzjLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class DmzjPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
        self.vol_index=0
    
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>',re.S|re.M).findall(content)[0]
        # cover
        cover_content=re.compile(r'/"><img(.*?) id="cover_pic"/></a>',re.S|re.M).findall(content)[0]
        self.comic.cover=re.compile(r'src="(.*?)"',re.S|re.M).findall(cover_content)[0]
        # description
        self.comic.description=re.compile(r'<div class="line_height_content">(.*?)<br/>',re.S|re.M).findall(content)[0].strip()
        # vols
        vols_content=re.compile(r'<div class="cartoon_online_border"(.*?)</div>',re.S|re.M).findall(content)
        self.handle_starttag=self.vols_collection
        for vol in vols_content:
            self.feed(vol)
    
    def vols_collection(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append(InfoVol('http://manhua.dmzj.com'+infos['href'],infos['title']))

class DmzjVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()

    def work(self,content):
        js_content=re.compile(r'\}\(\'(.*?).split',re.S|re.M).findall(content)[0]
        encs=re.compile(r'\[(.*?)\]',re.S|re.M).findall(js_content)[0].replace('\\','').replace('"','')
        vals=js_content.split(',')
        a,c,key_arr,dec_arr=int(vals[-3]),int(vals[-2])-1,vals[-1].replace("'",'').split('|'),{}
        while c>=0:
            idx=e_func(c,a)
            dec_arr[idx]=key_arr[c] or idx
            c-=1
        def rep(m):
            enc=m.group()
            dec=None
            try:
                dec=dec_arr[enc]
            except:
                dec=enc
            return dec
        pic_index=1
        for url in encs.split(','):
            url=re.subn(r'\w+',rep,url)[0].strip()
            self.pic_urls.append(('http://images.dmzj.com/'+url,zero_prefix(pic_index)))
            pic_index+=1

def to36(val):
    return toRadix(val,36)

def e_func(c,a):
    c,a=int(c),int(a)
    res=None
    if c<a: 
        res=''
    else:   
        res=e_func(int(c/a),a)
    c=c%a
    if c>35: 
        res+=chr(c+29)
    else: 
        res+=to36(c)
    return res
